<template>
  <text :style="`color: ${props.color};`" v-if="!remainingTime || state == 3">
    <i class="iconfont icon-time" />无计时</text
  >
  <text :style="`color: ${props.color};`" v-else>
    <i class="iconfont icon-time" /> {{ remainingTime }}</text
  >
</template>

<script lang="ts" setup>
import http from "@/utils/request.js";
import { computed, onMounted, onUnmounted, ref, watch } from "vue";

const emit = defineEmits(["end", "remind"]);
const props = withDefaults(
  defineProps<{
    expireTime?: Date;
    preTxt?: string;
    remind?: number;
    color?: string;
    state?: number;
  }>(),
  {
    preTxt: "",
    color: "$uni-base-color",
  }
);

const expireTime = ref(props.expireTime);
const curTime = ref(new Date());
const times = ref(0);
let timerId: number | undefined;  // 定义一个变量来存储定时器的ID

watch(
  () => props.expireTime,
  () => {
    expireTime.value = props.expireTime;
  }
);

const remainingTime = computed(() => {
  if (!expireTime.value) return "-";

  const timeDifference = expireTime.value.getTime() - curTime.value.getTime();
  if (timeDifference <= 0) {
    // 如果时间差小于等于零，表示已过期
    return "";
  } else {
    // 计算剩余时间各部分
    const totalSeconds = Math.floor(timeDifference / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
  }
});

onMounted(async () => {
  synTime();
});

onUnmounted(() => {
  clearTimeout(timerId);  // 清除定时器
});

async function synTime() {
  if (!expireTime.value) {
    timerId = setTimeout(synTime, 1000);
    return;
  }

  if (times.value <= 0) {
    times.value = 30;
    let { data } = await http.post("login/sysTime", {});
    curTime.value = new Date(data.replaceAll("-", "/"));
  } else {
    curTime.value = new Date(curTime.value.getTime() + 1000);
    times.value--;
  }

  if (props.remind) {
    if (
      curTime.value.getTime() + props.remind * 1000 >=
      expireTime.value.getTime()
    ) {
      emit("remind");
    }
  }

  if (curTime.value.getTime() >= expireTime.value.getTime()) {
    emit("end");
    return;
  }

  timerId = setTimeout(synTime, 1000);
}
</script>

<style lang="scss" scoped>
span {
  font-weight: bold;
  font-size: 14px;
  color: var(--el-color-primary);
  margin: auto;
  display: block;
  text-align: center;
}
</style>
